package com.cityguardian.threads;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cityguardian.cityguardianapp.MapActivity;
import com.cityguardian.model.Entidad;
import com.cityguardian.model.Usuario;
import com.google.android.gms.maps.model.LatLng;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;

public class AsyncTaskFoursquare extends AsyncTask<String, Double, String>  {
		
	public final static String RADIO = "10000";//en metros
	public final static String CLIENT_ID = "C50CGXC0BJ3HMX5ZKPEDTWSKERUCXNY1LCQ4GLWPBV3XH3YX";
	public final static String CLIENTE_SECRET = "4WGR0MQJKAZV2NW2KASNJIZTD3XFRPQGEEOPXEQHVI5WDXTO";
	private ActionBarActivity activity;
	private LatLng position;
	private String buscar;
	private ArrayList<Entidad> entidades;
	private ProgressDialog dialog;
	private Usuario usuario;
	
	public AsyncTaskFoursquare(ActionBarActivity activ,LatLng lastPosition, String busqueda, Usuario usuario) {
		this.activity = activ;
		this.position = lastPosition;
		this.buscar = busqueda;
		this.usuario = usuario;
		this.dialog = new ProgressDialog(activity);
	}
	
	@Override
    protected void onPreExecute() {
        this.dialog.setMessage("Buscando...");
        this.dialog.show();
    }

	@Override
	protected String doInBackground(String... arg0) {
		String response=doSomething();
		try {
			JSONObject jsonObject= new JSONObject(response);
			JSONObject subObject = jsonObject.getJSONObject("response");
			JSONArray array = subObject.getJSONArray("venues");
			//Log.d("array",array.toString());
			entidades = new ArrayList<Entidad>();
			for (int i=0;i<array.length();i++){
				JSONObject jsonEntidad = array.getJSONObject(i);
				Entidad entidad = new Entidad();
				entidad.setId(jsonEntidad.optString("id"));
				entidad.setName(jsonEntidad.optString("name"));
				JSONObject jsonContact = jsonEntidad.getJSONObject("contact");
				entidad.setTelefono(jsonContact.optString("phone"));
				JSONObject jsonLocation = jsonEntidad.getJSONObject("location");
				entidad.setDireccion(jsonLocation.optString("address"));
				entidad.setLatitud(jsonLocation.optString("lat"));
				entidad.setLongitud(jsonLocation.optString("lng"));
				entidad.setDistancia(jsonLocation.optString("distance"));
				entidad.setCiudad(jsonLocation.optString("city"));
				entidad.setTipo(buscar);
				entidades.add(entidad);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		return ((response!=null)?"1":null);
	}
	
	@Override
	protected void onPostExecute(String result) {
		if (this.dialog.isShowing()) {
			this.dialog.dismiss();
		}
		if (result!=null){
			Intent intent = new Intent(this.activity, MapActivity.class);
			intent.putExtra("Usuario", usuario);
			intent.putExtra("Busqueda", buscar);
			intent.putExtra("Entidades", entidades);
			activity.startActivity(intent);
			
			return;
		}
	}

	private String doSomething() {
		String timeStamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
		HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
		String url = "https://api.foursquare.com/v2/venues/search?client_id="
				+CLIENT_ID+"&client_secret="+CLIENTE_SECRET+"&v="+timeStamp
				+"&ll="+position.latitude+","+position.longitude+"&query="
				+buscar+"&radius="+RADIO;
		try {
            response = httpclient.execute(new HttpGet(url));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
                //Log.d("GET",responseString);
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
	}
	
}
